const path = require("path");
const TerserPlguin = require("terser-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { ProvidePlugin } = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  mode: "production",
  entry: "./src/main.js",
  devtool: false,
  output: {
    filename: "js/[name]_[chunkhash:5].js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
    chunkFilename: "js/[name]_[chunkhash:5].js", // 为小的chunk进行命名
    // publicPath: "http://coderwhy.com", // cdn服务器地址
  },
  // externals: {
  //   // 排除哪些包不需要打包
  //   // key属性名：排除框架的名称，import导入的是什么，这里就些什么
  //   // value属性值：第三方包导出的变量
  //   react: "React",
  //   axios: "axios",
  // },
  target: "web",
  optimization: {
    chunkIds: "deterministic",
    splitChunks: {
      chunks: "all",
      // maxSize: 20000,
      // minSize: 10,
      cacheGroups: {
        utils: {
          test: /utils/,
          filename: "js/[name]_utils.js",
        },
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          filename: "js/[name]_vendors.js",
        },
      },
    },
    minimizer: [
      new TerserPlguin({
        parallel: true,
        terserOptions: {},
      }),
    ],
  },
  devServer: {
    static: ["public", "common"],
    liveReload: false,
    host: "0.0.0.0",
    port: "3000",
    open: true,
    compress: true,
    historyApiFallback: true,
    proxy: [
      {
        context: ["/api", "/auth"],
        target: "http://123.207.32.32:9002",
        changeOrigin: true,
        pathRewrite: {
          "^/api": "",
        },
      },
    ],
  },
  resolve: {
    extensions: [".js", ".json", ".jsx", ".vue", ".ts"],
  },
  module: {
    rules: [
      {
        test: /\.m?jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /\.ts$/,
        use: ["babel-loader"],
      },
      {
        test: /\.css$/,
        // use: ["style-loader", "css-loader"],
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  plugins: [
    new TerserPlguin(),
    new HtmlWebpackPlugin({
      template: "./index.html",
    }),
    // 本地开发使用shimming（需要打包），线上使用cdn（不需要打包，externals排除掉，在index.html中引入）
    new ProvidePlugin({
      axios: ["axios", "default"],
      dayjs: "dayjs",
    }),
    new MiniCssExtractPlugin({
      filename: "css/[name]_[hash:6].css",
      chunkFilename: "css/[name]_[hash:6].css",
    }),
  ],
};
